package com.mumu.android.utm;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

public class AbduLocationService extends Service implements LocationListener {
    private LocationManager locationManager;
    private Location currentLocation, locationManagerNetWork;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        System.out.println("位置服务初始化");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        getCurrentLocation();
        System.out.println("位置服务启动");
        return START_STICKY;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        stopLocationUpdates();
        System.out.println("位置服务销毁");
    }

    private void getCurrentLocation() {
        try {
            locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
            locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, new LocationListener() {
                @Override
                public void onLocationChanged(@NonNull Location location) {
                    System.out.println("网络定位");
                    sendData(location);
                }
            });


            currentLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
            if (currentLocation != null) {

            }
        } catch (SecurityException e) {
            e.printStackTrace();
        }
    }

    private void stopLocationUpdates() {
        locationManager.removeUpdates(this);
    }

    @Override
    public void onLocationChanged(Location location) {
        currentLocation = location;
        // 处理位置更新
        System.out.println("位置服务变化");
        System.out.println("位置："+location.getLongitude());
        sendData(location);
    }
    @Override
    public void onProviderEnabled(String provider) {
    }

    @Override
    public void onProviderDisabled(String provider) {
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
    }


    private void sendData(Location location){
        Intent intent = new Intent("com.abdusalam.Location_Data");
        intent.putExtra("longitude", location.getLongitude());
        intent.putExtra("latitude", location.getLatitude());
        intent.putExtra("speed", location.getSpeed());
        intent.putExtra("bearing", location.getBearing());
        intent.putExtra("altitude", location.getAltitude());
        sendBroadcast(intent);
    }
}
